package codetop.microsoft.T907;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author: 18362
 * @Create: 2022-09-07 14:48:09 星期三
 */
class Solution {

    private static final long mod = 1000000007;

    public int sumSubarrayMins(int[] arr) {
        int[] rightSmall = findNextSmall(arr, arr.length, arr.length - 1, -1, -1, true);
        int[] leftSmall = findNextSmall(arr, -1, 0, arr.length, 1, false);
        long res = 0;
        for (int i=0; i<arr.length; ++i) {
            int leftNum = i - leftSmall[i] - 1, rightNum = rightSmall[i] - i - 1;
            int cnt = (leftNum == 0 ? 1 : leftNum + 1) * (rightNum == 0 ? 1 : rightNum + 1);
            res = (res + (long) cnt * arr[i]) % mod;
        }
        return (int) res;
    }

    private int[] findNextSmall(int[] arr, int defaultValue, int start, int end, int step, boolean contain) {
        Deque<Integer> dq = new LinkedList<>();
        int[] res = new int[arr.length];
        for (int i=start; i!=end; i+=step) {
            while (!dq.isEmpty() && arr[dq.getLast()] >= arr[i]) {
                if (arr[dq.getLast()] >= arr[i]) {
                    if (contain && arr[dq.getLast()] == arr[i])
                        break;
                    else
                        dq.removeLast();
                } else
                    break;
            }

            res[i] = dq.isEmpty() ? defaultValue : dq.getLast();
            dq.addLast(i);
        }
        return res;
    }
}